package com.imooc.api;

import com.alibaba.fastjson.JSONObject;
import com.imooc.api.support.UserSupport;
import com.imooc.bilibili.domain.*;
import com.imooc.bilibili.service.UserFollowingService;
import com.imooc.bilibili.service.UserService;
import com.imooc.bilibili.util.RSAUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * ProjectName imooc-bilibili
 *
 * @author xieyucan
 * <br>CreateDate 2022/10/21 18:03
 */
@RestController
public class UserApi {
    @Resource
    private UserService userService;

    @Resource
    private UserSupport userSupport;

    @Resource
    private UserFollowingService userFollowingService;

    @GetMapping("/users")
    public JsonResponse<User> getUserInfo()
    {
        Long userId = userSupport.getCurrentUserId();
        User userInfo = userService.getUserInfo(userId);
        return new JsonResponse<>(userInfo);
    }

    @GetMapping("/rsa-pks")
    public JsonResponse<String> getRsaPublicKey(String password) throws Exception {
        String pk = RSAUtil.encrypt(password);
        return new JsonResponse<>(pk);
    }



    @PostMapping("/users")
    public JsonResponse<String> addUser(@RequestBody User user)
    {
        userService.addUser(user);
        return JsonResponse.success();
    }


    @PostMapping("/user-tokens")
    public JsonResponse<String> login(@RequestBody User user) throws Exception {
        String token=userService.login(user);
        return new JsonResponse<>(token);
    }


    @PutMapping("/users")
    public JsonResponse<String> updateUser(@RequestBody User user)
    {
        Long userId = userSupport.getCurrentUserId();
        user.setId(userId);
        userService.updateUser(user);
        return JsonResponse.success();
    }

    @PutMapping("/user-infos")
    public JsonResponse<String> updateUserInfo(@RequestBody UserInfo userInfo)
    {
        Long userId = userSupport.getCurrentUserId();
        userInfo.setUserId(userId);
        userService.updateUserInfo(userInfo);
        return JsonResponse.success();
    }

    @GetMapping("/user-info")
    public JsonResponse<PageResult<UserInfo>> pageListUserInfo(@RequestParam Integer no, @RequestParam Integer size, String nick)
    {
        Long userId = userSupport.getCurrentUserId();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("no",no);
        jsonObject.put("size",size);
        jsonObject.put("nick",nick);
        jsonObject.put("userId",userId);
        PageResult<UserInfo> pageResult=userService.pageListUserInfo(jsonObject);
        if(pageResult.getTotal()>0)
        {
            List<UserInfo> checkFollowStatus=userFollowingService.checkFollowStatus(pageResult.getList(),userId);
            pageResult.setList(checkFollowStatus);
        }
        return new JsonResponse<>(pageResult);
    }
}
